// db/index.js
const mysql = require('mysql2/promise');
require('dotenv').config();

// 使用环境变量连接到现有数据库
const pool = mysql.createPool({
  host: process.env.MYSQL_HOST,
  port: process.env.MYSQL_PORT || 3306,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

// 测试连接
const testConnection = async () => {
  try {
    const connection = await pool.getConnection();
    console.log('MySQL数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('MySQL数据库连接失败:', error);
    return false;
  }
};

module.exports = {
  pool,
  testConnection,
};
